package ebj.common.document_create.helper;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfTemplate;
import com.itextpdf.text.pdf.PdfWriter;

public class HeaderFooter extends PdfPageEventHelper{
    PdfTemplate total;
    
    @Override
    public void onOpenDocument(PdfWriter writer, Document document) {
        // TODO Auto-generated method stub
        super.onOpenDocument(writer, document);
        total = writer.getDirectContent().createTemplate(30,16);
    }

    @Override
    public void onEndPage (PdfWriter writer, Document document) {
        Rectangle rect = writer.getBoxSize("art");
        Font headerFooterFont = ITextHelper.getChineseFont(10, Font.BOLD);
        switch(writer.getPageNumber() % 2) {
        case 0:
            ColumnText.showTextAligned(writer.getDirectContent(),
                    Element.ALIGN_RIGHT, new Phrase("event-header   偶数页-页眉-内容", headerFooterFont ),
                    rect.getRight(), rect.getTop(), 0);
            break;
        case 1:
            ColumnText.showTextAligned(writer.getDirectContent(),
                    Element.ALIGN_LEFT, new Phrase("odd-header  奇数页-页眉-内容", headerFooterFont),
                    rect.getLeft(), rect.getTop(), 0);
            break;
        }
        ColumnText.showTextAligned(writer.getDirectContent(),
                Element.ALIGN_CENTER, new Phrase(String.format("第 %d 页", writer.getPageNumber()), headerFooterFont),
                (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
    }

    @Override
    public void onCloseDocument(PdfWriter writer, Document document) {
        // TODO Auto-generated method stub
        super.onCloseDocument(writer, document);
        Rectangle rect = writer.getBoxSize("art");
        Font headerFooterFont = ITextHelper.getChineseFont(10, Font.BOLD);
        String text = String.format("共%s页", String.valueOf(writer.getPageNumber()));  
        ColumnText.showTextAligned(total, Element.ALIGN_LEFT, new Phrase(text, headerFooterFont), (rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
    }
}